/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pyin
 */
public class WinCMD {

    private String cmd;

    public WinCMD(String cmd) {
        this.cmd = cmd;
    }

    public class StreamReader extends Thread {

        private InputStream is;
        private StringWriter sw;

        StreamReader(InputStream is) {
            this.is = is;
            sw = new StringWriter();
        }

        public void run() {
            try {
                int c;
                while ((c = is.read()) != -1) {
                    sw.write(c);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String getResult() {
            return sw.toString();
        }
    }

    public String run() throws WinCMDFailedException {
        try {
            Process process = Runtime.getRuntime().exec(this.cmd);
            StreamReader reader = new StreamReader(process.getInputStream());
            reader.start();
            if (process.waitFor() == 0) {
                reader.join();
                return reader.getResult();
            } else {
                throw new WinCMDFailedException();
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(WinCMD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(WinCMD.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "Failed to execute command";
    }

    public class WinCMDFailedException extends Exception{
        @Override
        public String getMessage(){
            return "Command failed.";
        }
    }

    public static void main(String[] args) {
        
            WatchedFile pwd = new WatchedFile("C:\\a");
            System.out.println(pwd.hashCode());
//            System.out.println(new WinCMD("net use \\ops-xian").run());

    }
}
